package matse11.LSpielProject;

import java.io.*;
import java.util.Scanner;

import android.content.Context;

public class HighScore {
	private String [] name = new String[10];
	private int [] zuege = new int[10];
	private Context context;
	
	public HighScore(Context context){
		this.context=context;
		leseHS();
	}
	public void leseHS(){
		
		String s;
		
		int i=0;
			FileInputStream myFileIn;
			try {
				myFileIn = context.openFileInput("highscore.txt");
				Scanner mySc = new Scanner(myFileIn);
				while(mySc.hasNextLine()){
					s = mySc.nextLine();
					name[i] = s.split(",")[0];
					zuege[i] = Integer.parseInt(s.split(",")[1]);
					//System.out.println(name[i]+" , "+zuege[i]);
					i++;
					
				}
				myFileIn.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			
			
				
	
	}
	
	private void schreibeHS(){
		try {
			FileOutputStream myFileOut = context.openFileOutput("highscore.txt", Context.MODE_PRIVATE);
			PrintWriter pw = new PrintWriter(myFileOut);
			for (int i = 0; i < name.length; i++) {
				pw.println(name[i]+","+zuege[i]);
			}
			pw.close();
			myFileOut.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	public boolean vergleiche(String name,int zuege){
		boolean best=false;
		name = name.replace(",", "");
		if(zuege > this.zuege[9]){
			for (int i = 0; i < this.name.length; i++) {
				if(zuege > this.zuege[i]){
					setzeScore(name, zuege, i);
					schreibeHS();
					best = true;
					break;
				}
			}
		}
		
		return best;
	}
	
	private void setzeScore(String name, int zuege, int index){
		for(int i=9; i>=index;i--)
			if(i!=index){
				this.name[i]=this.name[i-1];
				this.zuege[i]=this.zuege[i-1];
			}
			else{
				this.name[i]=name;
				this.zuege[i]=zuege;
				
			}
	}

	public String spielerToString(){
		String res = "";
		for (int i = 0; i < name.length; i++) {
			res += (i+1)+")  "+(!name[i].equals("null") ? name[i] : "")+"\n";
		}
		return res;
	}
	
	public String zuegeToString(){
		String res = "";
		for (int i = 0; i < zuege.length; i++) {
			res += (zuege[i] != 0 ? zuege[i] : "")+"\n";
		}
		return res;
	}
}
